package com.dishdex.menuhub.app.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * ClassName:
 * Package: com.dishdex.menuhub.app.controller
 * Description:
 *
 * @Author:
 * @Create 2025/11/3 16:02
 * @Version 1.0
 */
@RestController
@Slf4j
public class TestController {

    @RequestMapping("/unsafe")
    public String unsafe() throws InterruptedException {
        int clientTotal = 5000;
        int threadTotal = 200;
        StringBuilder sb = new StringBuilder();
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    sb.append("1");
                    semaphore.release();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}", sb.length());
        return String.valueOf(sb.length());

    }


    @RequestMapping("/safe")
    public String safe() throws InterruptedException {
        int clientTotal = 5000;
        int threadTotal = 200;
        StringBuffer sb = new StringBuffer();
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    sb.append("1");
                    semaphore.release();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}", sb.length());
        return String.valueOf(sb.length());

    }
}
